<?php
namespace ac\component\tool;

use Yii;
use app\models\HttprequestLog;
use ac\component\tool\Tool;
use yii\httpclient\Client;
use yii\httpclient\Request;
use yii\httpclient\RequestEvent;


/*
请求类
参考地址:
https://github.com/yiisoft/yii2-httpclient/tree/master/docs/guide-zh-CN
https://segmentfault.com/a/1190000019907511?utm_source=tag-newest
https://www.cnblogs.com/chrdai/p/10612841.html
*/
class HttpClient
{

    public $baseUrl;//基础域名
    public $url = '';//参数,比如'/site/index',其实可以放到$baseUrl上面
    public $data = [];//需要传递的参数
    public $timeout = 5;//允许执行请求的最大超时时间（秒）
    private $requesttime;//请求时间
    private $responsetime;//响应时间
    private $requestWay = 2;//请求方式 1-GET 2-POST
    private $logid = 0;//主键值

    public function __construct($baseUrl)
    {
        $this->baseUrl = $baseUrl;
    }


    public function get()
    {
        $client = new Client([
            'baseUrl' => $this->baseUrl //接口的入口地址
        ]);
        $request = $client
            ->get($this->url, $this->data)
            ->setOptions([
                'timeout' => $this->timeout, // connection timeout
            ]);

        /*请求前*/
        $request->on(Request::EVENT_BEFORE_SEND, function (RequestEvent $event) {
            $this->beforeSend($event);
        });
        /*请求后*/
        $request->on(Request::EVENT_AFTER_SEND, function (RequestEvent $event) {
            $this->afterSend($event);
        });

        $response = $request->send();
        // P($response->data);
        if (!$response->isOk) {//接口请求错误
            return false;
        }else{
            $this->requestWay = 1;
            //接口返回信息
            if(!empty($response->data)){
                return $response->data;
            }else{
                return true;
            }
        }

        return false;
    }

    public function post()
    {
        $client = new Client([
            'baseUrl' => $this->baseUrl, //接口的入口地址
            // 'requestConfig' => [
            //     'format' => Client::FORMAT_JSON
            // ],
            'responseConfig' => [
                'format' => Client::FORMAT_JSON
            ],
        ]);
        $request = $client->createRequest()
            ->setMethod('POST')
            // ->setMethod('GET')
            // ->setFormat(Client::FORMAT_JSON)
            ->setUrl($this->url)
            ->setHeaders([
                'Content-Type'=>'application/json'
            ])
            // ->setFormat(Client::FORMAT_JSON)
            ->setOptions([
                'timeout' => $this->timeout, // connection timeout
            ])
            ->setData($this->data);

        /*请求前*/
        $request->on(Request::EVENT_BEFORE_SEND, function (RequestEvent $event) {
            $this->beforeSend($event);
        });
        /*请求后*/
        $request->on(Request::EVENT_AFTER_SEND, function (RequestEvent $event) {
            $this->afterSend($event);
        });



        $response = $request->send();

        if (!$response->isOk) {//接口请求错误
            return false;
        }else{
            // P($response->data, false);
            // echo '3';
            //接口返回信息
            if(!empty($response->data)){
                return $response->data;
            }else{
                return true;
            }
        }

        return false;
    }

    /*请求前事件*/
    private function beforeSend($event)
    {
        $requestData = $event->request->getData();
        $this->requesttime = Tool::getMsectime();
        // P($requestData, false);


        $url = Yii::$app->request->hostInfo . Yii::$app->request->getUrl();//当前完整URL
        $this->responsetime = Tool::getMsectime();
        /*存入日志*/
        $data = array(
            "app_info_id" => isset($requestData['appInfoId'])?$requestData['appInfoId']:0,
            "request_url" => $url,//请求完整URL
            "request_data" => json_encode($requestData),//请求值
            "request_cookies" => json_encode($_COOKIE),//请求cookie
            "request_ip" => Yii::$app->request->userIP,//请求ip
            "request_way" => $this->requestWay,//请求方式
            "requesttime" => $this->requesttime,//请求时间
            "response_url" => $this->baseUrl . $this->url,//响应端URL
            "response_data" => '',//响应值
            "responsetime" => 0,//响应时间
            "isok" => 2,//请求是否成功1-是2-否
            "add_time" => date("Y-m-d H:i:s", time()),
        );
        // P($data);
        $this->logid = HttprequestLog::add($data);
    }


    /*请求后事件*/
    private function afterSend($event)
    {
        try{
            $responseData = $event->response->getData();
        }catch(\Exception $exception){
            echo 'HttpClient 没有收到返回值';
            P($exception);
        };
        $this->responsetime = Tool::getMsectime();

        /*返回数据 更新到表*/
        HttprequestLog::updateAll(['response_data' => json_encode($responseData), 'responsetime' => $this->responsetime, 'isok' => 1], 'log_id = :id', [':id' => $this->logid]);

    }

}